<template>
  <div class="create">
    <h2>{{ $route.params.id ? "编辑" : "创建" }}分类</h2>
    <el-form ref="form" :model="form" label-width="80px">
      <el-form-item label="名称">
        <el-input v-model="form.name"></el-input>
      </el-form-item>
      <el-form-item label="用法">
        <el-input v-model="form.usage"></el-input>
      </el-form-item>
      <el-form-item label="图标">
        <el-upload
          class="avatar-uploader"
          :action="$http.defaults.baseURL + '/upload'"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="form.icon" :src="form.icon" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSubmit">{{
          $route.params.id ? "修改保存" : "立即创建"
        }}</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      form: {
        id: "",
        name: "",
        icon: null,
      },
      parentList: [],
    };
  },
  methods: {
    async getParent() {
      const res = await this.$http.get("common/items");
      this.parentList = res.data;
    },
    async onSubmit() {
      console.log("submit!");
      let url =
        this.form.id == "" ? "common/items" : "common/items/edit";
      const res = await this.$http.post(url, this.form);
      console.log(res);

      this.$message({
        type: "success",
        message: this.form.id == "" ? "创建成功!" : "修改成功",
      });

      this.form = {
        id: "",
        name: "",
        parent: null,
      };
      this.getParent();
    },
    async getItem(id) {
      const res = await this.$http.get(`common/items/${id}`);
      this.form = res.data;
    },
    handleAvatarSuccess(res) {
      this.form.icon = res.url
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
  },
  created() {
    this.$route.params.id && this.getItem(this.$route.params.id);
  },
  mounted() {
    this.getParent();
  },
};
</script>